<script setup>
import { ref, reactive, onMounted, watch } from "vue";
import { SortUp, SortDown, ShoppingCart, CollectionTag } from "@element-plus/icons-vue";

import { useRouter, useRoute } from "vue-router";
import axios from "axios";
import { useI18n } from "vue-i18n";
const I18n = useI18n();
const { locale } = useI18n();

const router = useRouter();
const route = useRoute();
const id = ref(parseInt(route.query.id));
const subid = ref(parseInt(route.query.subid));

// 跳转页面
const jumpTo = (path) => {
  router.push(path);
};

// 二级分类列表
let subTypeList = ref([]);

// 当前选中的二级分类
let activeSubType = ref(0);

// 选中二级分类
const selSubType = (type) => {
  activeSubType.value = type;
  getProductList();
};

// 价格排序状态
let priceSort = ref(""); // 0价格未进行排序，1价格上升，2价格下降
let salesOrder = ref("");
// 上架时间
let shelfTime = ref(0); // 0上架时间未进行排序，1上架时间上升，2上架时间下降

// 修改排序状态
const changeSortType = (type) => {
  // 0为默认，1为价格排序，2为上架时间排序
  if (type === 0) {
    priceSort.value = "";
    salesOrder.value = "";
  } else if (type === 1) {
    salesOrder.value = "";
    if (priceSort.value == "asc") {
      priceSort.value = "desc"; // 下降
    } else if (priceSort.value == "desc") {
      priceSort.value = "asc"; // 上升
    } else {
      priceSort.value = "asc"; // 上升
    }
  } else if (type === 2) {
    priceSort.value = "";
    if (salesOrder.value == "asc") {
      salesOrder.value = "desc"; // 下降
    } else if (salesOrder.value == "desc") {
      salesOrder.value = "asc"; // 上升
    } else {
      salesOrder.value = "asc"; // 上升
    }
  }
  getProductList();
};

const category = ref(null);
// 产品列表
const productList = ref([]);

const getCategoryList = async () => {
  try {
    const res = await axios.get(`${apiUrl}/category`, {
      headers: {
        "Authori-zation": `Bearer ${getToken()}`,
      },
    });

    if (res.data.status === 200) {
      if (!id.value) {
        category.value = res.data.data[0];
      } else {
        category.value = res.data.data.filter((item) => item.id === id.value)[0];
      }
      subTypeList.value = category.value.children;

      // 默认选中第一个
      selSubType(subTypeList.value[0].id);
    }
  } catch (e) {}
};

const getProductList = async () => {
  try {
    const res = await axios.get(
      `${apiUrl}/products?sid=${activeSubType.value}&keyword=&priceOrder=${priceSort.value}&salesOrder=${salesOrder.value}&news=0&page=1&limit=200&cid=0&coupon_category_id=&productId=`,
      {
        headers: {
          "Authori-zation": `Bearer ${getToken()}`,
        },
      }
    );

    if (res.data.status === 200) {
      productList.value = res.data.data;
    }
  } catch (e) {}
};

// 添加到购物车
const addCar = (product) => {
  for (let i = 0; i < productList.value.length; i++) {
    const element = productList.value[i];
    if (element.id === product.id) {
      element.isInCar = !element.isInCar;
    }
  }
};

const collectionProductList = ref([]);
const getCollectionProductList = async () => {
  try {
    const res = await axios.get(`${apiUrl}/collect/user?page=1&limit=100`, {
      headers: {
        "Authori-zation": `Bearer ${getToken()}`,
      },
    });

    if (res.data.status === 200) {
      collectionProductList.value = res.data.data.list;
    }
  } catch (e) {}
};

const inCollection = (product) => {
  for (let i = 0; i < collectionProductList.value.length; i++) {
    const element = collectionProductList.value[i];
    if (element.product_id === product.id) {
      return true;
    }
  }
  return false;
};

const addCollection = async (product) => {
  try {
    const res = await axios.post(
      `${apiUrl}/collect/add`,
      { id: product.id, product: "product" },
      {
        headers: {
          "Authori-zation": `Bearer ${getToken()}`,
        },
      }
    );
    getCollectionProductList();
  } catch (e) {}
};

const delCollection = async (product) => {
  try {
    const res = await axios.post(
      `${apiUrl}/collect/del`,
      { id: product.id, product: "product" },
      {
        headers: {
          "Authori-zation": `Bearer ${getToken()}`,
        },
      }
    );
    getCollectionProductList();
  } catch (e) {}
};

onMounted(async () => {});

watch(
  () => route.query,
  async (newQuery, oldQuery) => {
    id.value = parseInt(newQuery.id);
    subid.value = parseInt(newQuery.subid);
    await getCategoryList();
    getProductList();
  },
  { deep: true, immediate: true }
);
</script>

<template>
  <div class="topInfo" v-if="category !== null">
    <div class="middle">
      <div class="title">
        {{ locale === "zh-cn" ? category?.cate_name : category?.en_cate_name }}
      </div>
      <div class="desc">
        {{ locale === "zh-cn" ? category?.memo : category?.en_memo }}
      </div>

      <div class="subTypeList">
        <div
          class="item"
          v-for="item in subTypeList"
          :key="item.id"
          :class="{ active: activeSubType === item.id }"
          @click="selSubType(item.id)"
        >
          {{ locale === "zh-cn" ? item.cate_name : item.en_cate_name }}
        </div>
      </div>
    </div>
  </div>
  <div class="middle">
    <div class="filterBox">
      <div class="item">{{ $t("productList.sort") }}</div>
      <div
        class="item"
        :class="{ active: priceSort === '' && salesOrder === '' }"
        @click="changeSortType(0)"
      >
        {{ $t("productList.default") }}
      </div>
      <div class="item" :class="{ active: priceSort !== '' }" @click="changeSortType(1)">
        {{ $t("productList.price") }}
        <el-icon class="filterIcon" v-show="priceSort === 'asc'">
          <SortUp />
        </el-icon>
        <el-icon class="filterIcon" v-show="priceSort === 'desc'">
          <SortDown />
        </el-icon>
      </div>
      <div class="item" :class="{ active: salesOrder !== '' }" @click="changeSortType(2)">
        {{ $t("productList.sales") }}
        <el-icon class="filterIcon" v-show="salesOrder === 'asc'">
          <SortUp />
        </el-icon>
        <el-icon class="filterIcon" v-show="salesOrder === 'desc'">
          <SortDown />
        </el-icon>
      </div>
    </div>

    <div class="productList" v-if="productList.length > 0">
      <div
        class="item"
        v-for="item in productList"
        :key="item.id"
        @click="jumpTo('/productDetail?id=' + item.id)"
      >
        <div class="promotionInfo" v-if="item.promotion">
          {{ $t("productList.promotion") }}{{ item.promotion }}%
        </div>
        <div class="coverBox">
          <img :src="item.image" alt="" />
        </div>
        <div class="productInfo">
          <div class="name">
            {{ locale === "zh-cn" ? item.store_name : item.en_store_name }}
          </div>
          <!-- <div class="price">￥{{ item.price }}/{{ $t("productList.unit") }}</div> -->
           <div class="price">￥{{ item.price }}</div>
        </div>

        <div class="btnBox" v-if="locale === 'zh-cn'">
          <div
            class="btn"
            :class="{ isIn: item.isInCar }"
            @click.stop="jumpTo('/productDetail?id=' + item.id)"
          >
            <el-icon :size="20"><ShoppingCart /></el-icon>
          </div>
          <div
            class="btn"
            :class="{ isIn: inCollection(item) }"
            @click.stop="
              isLogined() &&
                (inCollection(item) ? delCollection(item) : addCollection(item))
            "
          >
            <el-icon :size="20"><CollectionTag /></el-icon>
          </div>
        </div>
      </div>
    </div>
    <div v-else class="noProduct">
      <el-empty description="暂无产品"></el-empty>
    </div>
  </div>
</template>

<style scoped lang="scss">
.topInfo {
  // background-color: #000;
  width: 100%;
  height: 350px;
  background-image: url("/img/bg3.jpg");
  background-size: contain;
  background-position: center center;
  position: relative;

  &::before {
    content: "";
    position: absolute;
    inset: 0;
    background: rgba(0, 0, 0, 0.5);
    pointer-events: none;
    z-index: 0;
  }

  .middle {
    color: #fff;
    position: relative;
    z-index: 1;
    height: 100%;
    overflow: hidden;

    .title {
      font-size: 32px;
      font-weight: bold;
      margin-top: 60px;
      margin-bottom: 30px;
    }

    .desc {
      font-size: 20px;
      width: 400px;
      line-height: 30px;
    }

    .subTypeList {
      position: absolute;
      bottom: 30px;
      display: flex;

      .item {
        border: 1px solid #fff;
        margin-right: 20px;
        padding: 5px 20px;
        cursor: pointer;

        &.active {
          background-color: #fff;
          color: #000;
        }

        &:hover {
          background-color: #fff;
          color: #000;
        }
      }
    }
  }
}

.filterBox {
  display: flex;
  margin-top: 20px;
  color: #666;

  .item {
    margin-right: 30px;
    cursor: pointer;

    &.active {
      font-weight: bold;
      color: #000;
    }
  }
}

.filterIcon {
  position: relative;
  top: 2px;
}

.productList {
  display: flex;
  flex-wrap: wrap;
  margin-top: 15px;
  .item {
    width: 325px;
    padding-bottom: 65px;
    cursor: pointer;
    transition: 0.5s all;
    position: relative;
    &:hover {
      box-shadow: 0px 0px 4px 1px #c5c5c54f;

      .promotionInfo {
        display: block;
      }

      .btnBox {
        display: flex;
      }
    }

    .coverBox {
      width: 200px;
      height: 200px;
      margin: 30px auto 20px auto;
      user-select: none;

      img {
        width: 100%;
        height: 100%;
      }
    }

    .promotionInfo {
      display: block;
      position: absolute;
      right: 0;
      top: 0;
      padding: 5px 10px;
      background-color: #156197;
      color: #fff;
      transition: 0.5s all;
    }

    .productInfo {
      margin-top: 10px;
      .name {
        text-align: center;
        font-size: 16px;
        font-weight: bold;
      }

      .price {
        font-size: 16px;
        text-align: center;
        margin-top: 10px;
      }
    }

    .btnBox {
      display: none;
      transition: 0.5s all;
      position: absolute;
      justify-content: center;
      width: 100%;
      margin-top: 10px;

      .btn {
        width: 35px;
        height: 35px;
        background-color: #fff;
        color: #000;
        border: 1px solid #000;
        border-radius: 35px;
        // line-height: 40px;
        font-size: 35px;
        display: flex;
        justify-content: center;
        align-items: center;

        &:first-child {
          margin-right: 10px;
        }

        .el-icon {
          margin: auto;
        }

        &.isIn {
          background-color: #000;
          color: #fff;
          border: 1px solid #000;
        }
      }
    }
  }
}

.noProduct{
  padding: 50px;
}
</style>
